﻿using UnityEngine;
using System.Collections;

//用于控制多条血条的显示
public class BloodBarNumControl : MonoBehaviour {

    public BloodBarKit[] bloodArray;
    public float showTimer = 1f;//显示时间
    public int barNum = 1;//初始血条数目
    int nowBarNum;//表示从最高层数起的剩余条数，最大是barNum，最小是1
    float everyVal;//平均每条的血量占比

    public void Init()
    {
        barNum = Mathf.Clamp(barNum, 1, 5);
        SetShowNum(barNum);
        nowBarNum = barNum;
        everyVal = 1f / barNum;
    }

    void SetShowNum(int number)
    {
        for(int i = 0; i < bloodArray.Length; i++)
        {
            if (i < barNum)
            {
                bloodArray[i].gameObject.SetActive(true);
                bloodArray[i].SetValue(1);
            }
            else
            {
                bloodArray[i].gameObject.SetActive(false);
            }
        }
    }

    public void SetNowBarValue(float val, float showTime = 1.0f)
    {
        nowBarNum = barNum - Mathf.CeilToInt((1 - val) / everyVal) + 1;
        if (nowBarNum > barNum)
        {
            nowBarNum = barNum;
        }
        float value = 1 - (1 - val - everyVal * (barNum - nowBarNum)) / everyVal;
        bloodArray[nowBarNum - 1].SetValue(value);
        FreshBlood(nowBarNum);
        showTimer = showTime;
    }

    void FreshBlood(int number)
    {
        if(barNum > 1)
        {
            for (int i = barNum - 1; i >= number; i--)
            {
                if (bloodArray[i].val > 0)
                {
                    bloodArray[i].SetValue(0);
                }
            }
        }
    }

    void Update()
    {
        //val -= Time.deltaTime * 0.1f;
        //if (val >= 0)
        //    SetNowBarValue(val, 2);

        showTimer -= Time.deltaTime;
        if (showTimer <= 0)
        {
            gameObject.SetActive(false);
        }
    }

    public void Show(float showTime = 50)
    {
        showTimer = showTime;
        gameObject.SetActive(true);
    }

    public void Hide()
    {
        gameObject.SetActive(false);
    }
}
